package sk.vrto.service.email;

import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import sk.vrto.domain.Email;
import sk.vrto.domain.EmailAccount;
import sk.vrto.service.crypto.StringEncrypter;

import java.util.Properties;

/**
 * Implementation based on apache commons-mail
 */
public class EmailServiceImpl implements EmailService {

    private final Properties smtProperties;
    private final StringEncrypter encrypter;

    public EmailServiceImpl(Properties smtProperties, StringEncrypter encrypter) {
        this.smtProperties = smtProperties;
        this.encrypter = encrypter;
    }

    @Override
    public void send(EmailAccount from, Email email) {
        try {
            final HtmlEmail message = new HtmlEmail();
            message.setHostName(smtProperties.getProperty("mail.smtp.host"));
            message.setSmtpPort(Integer.parseInt(smtProperties.getProperty("mail.smtp.port")));
            message.setAuthenticator(new DefaultAuthenticator(
                    from.getEmailAddress(), encrypter.decrypt(from.getPassword())));
            message.setTLS(true);
            message.setFrom(from.getEmailAddress());
            message.setSubject(email.getTitle());
            message.setHtmlMsg(email.getContent());
            message.setMsg(email.getContent());
            message.addTo(email.getContact().getEmail());
            doSend(message);
        } catch (Exception e) {
            throw new RuntimeException("Unable to send mail", e);
        }

    }

    // mockable
    protected void doSend(org.apache.commons.mail.Email email) throws EmailException {
        email.send();
    }

}
